package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;

import com.example.demo.result.Result;
import com.example.demo.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;


@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法运行前运行返回tu're放行  返回false不放行
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 强制转换请求和响应对象为HttpServletRequest和HttpServletResponse
//        HttpServletRequest req = (HttpServletRequest) request;
//        HttpServletResponse resp = (HttpServletResponse) response;
//
//        // 获取请求的URL
//        String url = req.getRequestURL().toString();
//        // 记录拦截的请求
//        log.info("拦截请求:{}", url);
//
//        // 如果是登录请求，直接放行
//        if (url.contains("login")) {
//            log.info("登录请求,放行");
////            filterChain.doFilter(req, resp);
//
//            return true;
//        }
//
//        // 从请求头中获取JWT令牌
////        String jwt = req.getHeader("token");
//// 改为
//        String authorizationHeader = req.getHeader("Authorization");
//        String jwt = null;
//        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
//            jwt = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
//        }
//        // 如果没有携带JWT令牌，返回未登录错误
//        if (!StringUtils.hasLength(jwt)) {
//            log.info("未携带token,拦截");
//            Result error = Result.error("NOT_LOGIN");
//            // 将错误结果转换为JSON字符串
//            String notLogin = JSONObject.toJSONString(error);
//            resp.getWriter().write(notLogin);
//            return false;
//        }
//
//        // 尝试解析JWT令牌，如果解析失败，返回未登录错误
//        try {
//            JwtUtils.parseJWT(jwt); // 解析jwt
//        } catch (Exception e) {
//            log.info("解析jwt失败");
//            Result error = Result.error("NOT_LOGIN");
//            // 将错误结果转换为JSON字符串
//            String notLogin = JSONObject.toJSONString(error);
//            resp.getWriter().write(notLogin);
//            return false;
//        }
//
//        // 如果JWT合法，放行请求
//        log.info("jwt合法,放行");
////        filterChain.doFilter(servletRequest, servletResponse);
//        return true;
//    }



    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            log.info("处理 OPTIONS 预检请求: {}", request.getRequestURL());
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        HttpServletRequest req = request;
        HttpServletResponse resp = response;

        String url = req.getRequestURL().toString();
        String path = req.getServletPath(); // 获取请求路径
        log.info("拦截请求URL:{}, 路径:{}", url, path);

        // 登录相关请求直接放行 - 使用equals进行精确匹配，避免模糊匹配问题
        if (path.equals("/User_login") || path.equals("/User_Register") || 
            path.equals("/HR_login") || path.equals("/HR_Register") ||
            path.equals("/User_unsafe_login") || path.equals("/User_unsafe_register")) {
            log.info("安全或不安全的登录/注册请求,精确匹配放行");
            return true;
        }
        
        // 同时保留原有的contains判断作为备选，确保兼容性
        if (url.contains("login") || url.contains("register")) {
            log.info("登录或注册请求,contains匹配放行");
            return true;
        }

        // 获取 Authorization 头
        String authorizationHeader = req.getHeader("Authorization");
        log.info("Authorization header: {}", authorizationHeader);

        String jwt = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            log.info("提取到的JWT token: {}", jwt);
        }

        if (!StringUtils.hasLength(jwt)) {
            log.info("未携带有效token,拦截");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        try {
            JwtUtils.parseJWT(jwt);
            log.info("JWT解析成功");
        } catch (Exception e) {
            log.info("解析jwt失败: {}", e.getMessage());
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        log.info("jwt合法,放行");
        return true;
    }


    @Override//目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override//请求处理完成之后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
